package cn.ghx.xboot.item.fav;

import cn.ghx.xboot.common.BaseContext;
import cn.ghx.xboot.item.Item;
import cn.ghx.xboot.item.ItemService;
import cn.ghx.xboot.mapper.ItemFavUserMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

@Service
public class ItemFavUserService {

    @Resource
    private ItemFavUserMapper baseMapper;

    private final ItemService itemService;

    @Lazy
    public ItemFavUserService(ItemService itemService) {
        this.itemService = itemService;
    }

    public Boolean toggleFav(String id, Boolean fav) {
        String openid = BaseContext.getOpenid();
        Assert.isTrue(StringUtils.hasText(openid),"请登录");
        if(!fav){
            return baseMapper.removeByFav(id,openid);
        }else{
            return baseMapper.saveFav(id,openid);
        }
    }

    public Boolean isFav(String itemId,String openid){
        return baseMapper.isFav(itemId,openid);
    }

    public Page<Item> query(String keyword, String openid, Integer page, Integer size) {
        Page<Item> rs =  baseMapper.query(keyword,openid,Page.of(page,size));
        rs.getRecords().forEach(itemService::wrapExtra);
        return rs;
    }
}
